from rest_framework import serializers
from .models import PendingUser
from django.contrib.auth.models import User
import random
from django.contrib.auth.hashers import make_password
from .services import send_verification_code, async_send_verification_code
import re


class UserRegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=True)
    password2 = serializers.CharField(write_only=True, required=True)
    luogu_uid = serializers.CharField(write_only=True, required=True)
    luogu_uid2 = serializers.CharField(write_only=True, required=True)

    class Meta:
        model = PendingUser
        fields = ['username', 'email', 'password', 'password2', 'luogu_uid', 'luogu_uid2']

    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError({"password": "Password fields didn't match."})

        if attrs.get('luogu_uid') and attrs.get('luogu_uid2'):
            if attrs['luogu_uid'] != attrs['luogu_uid2']:
                raise serializers.ValidationError({"luogu_uid": "Luogu UID fields didn't match."})

            # 检查 luogu_uid 是否为纯数字
            if not re.fullmatch(r'\d+', attrs['luogu_uid']):
                raise serializers.ValidationError({"luogu_uid": "Luogu UID must be a numeric string."})

        return attrs

    def create(self, validated_data):
        # 检查是否已经有相同用户名和邮箱的 PendingUser，删除旧的记录
        existing_pending_user = PendingUser.objects.filter(
            username=validated_data['username'],
            email=validated_data['email'],
            is_verified=False
        ).first()
        if existing_pending_user:
            existing_pending_user.delete()

        # 生成验证码
        verification_code = str(random.randint(100000, 999999))
        luogu_uid = validated_data.get('luogu_uid', '')

        # 对密码进行哈希处理
        hashed_password = make_password(validated_data['password'])

        # 创建新的 PendingUser
        pending_user = PendingUser.objects.create(
            username=validated_data['username'],
            email=validated_data['email'],
            password=hashed_password,  # 存储哈希后的密码
            luogu_uid=luogu_uid,
            verification_code=verification_code,
        )

        # # 发送邮件验证码
        # send_verification_code(pending_user, verification_code)
        # 异步发送邮件验证码
        async_send_verification_code(pending_user, verification_code)

        return pending_user


class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise serializers.ValidationError("Invalid username or password.")

        if not user.check_password(password):
            raise serializers.ValidationError("Invalid username or password.")

        attrs['user'] = user
        return attrs
